package com.jn.erp.web.api.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jn.erp.web.api.sys.entity.SysDictData;
import com.jn.erp.web.api.sys.mapper.SysDictDataMapper;
import com.jn.erp.web.api.sys.service.SysDictDataService;
import com.jn.erp.web.api.sys.utils.DictUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/8/28 15:45
 */
@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements SysDictDataService {
    @Override
    public int insertDictData(SysDictData data) {
        int row = baseMapper.insert(data);
        if (row > 0) {
            List<SysDictData> dictDatas = selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
        return row;
    }

    @Override
    public int updateDictData(SysDictData data) {
        int row = baseMapper.updateById(data);
        if (row > 0) {
            List<SysDictData> dictDatas = selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
        return row;
    }

    @Override
    public void deleteDictDataByIds(Long[] dictCodes) {
        for (Long dictCode : dictCodes) {
            SysDictData data = baseMapper.selectById(dictCode);
            baseMapper.deleteById(dictCode);
            List<SysDictData> dictDatas = selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
    }

    public List<SysDictData> selectDictDataByType(String dictType) {
        QueryWrapper<SysDictData> qw = new QueryWrapper();
        qw.eq("status", "0");
        qw.eq("dict_type", dictType);
        List<SysDictData> dictDatas = baseMapper.selectList(qw);
        return dictDatas;

    }

    @Override
    public String getDictDataNameByType(String dictType,Object dictValue) {
        QueryWrapper<SysDictData> qw = new QueryWrapper();
        qw.eq("status", "0");
        qw.eq("dict_type", dictType);
        qw.eq("dict_value", dictValue);
        SysDictData dictDatas = baseMapper.selectOne(qw);
        return dictDatas.getDictLabel();

    }
}
